package br.com.robot.implement.steam;

import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import br.com.model.Game;
import br.com.model.dao.DAOFactory;
import br.com.robot.RobotBean;
import br.com.robot.RobotConfigurationBasic;
import br.com.robot.RobotList;
import br.com.robot.implement.AbstractRobot;
import br.com.robot.util.RobotsUtils;
import br.com.util.ER;
import br.com.util.Web;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.parser.HtmlParseData;

public class Steam_Games extends AbstractRobot
{
	@Override
	public List<String> configuraSeeds( )
	{
		return RobotsUtils.buscaSeeds( RobotList.ID_STEAM_ROBOT );
	}

	@Override
	public RobotConfigurationBasic infConfig( )
	{
		RobotConfigurationBasic configs = new RobotConfigurationBasic( )
			.setFollowRedirect  ( true                        )
			.setNumeroCrawllersm( 30                          )
			.setProfundidade    ( 0                           )
			.setRobots          ( Arrays.asList( infBean( ) ) );
		
		return configs;
	}

	@Override
	public RobotBean<? extends AbstractRobot> infBean( )
	{
		return RobotList.getBean( RobotList.ID_STEAM_GAMES_ROBOT );
	}
	
	@Override
	public void onStart( )
	{
		super.onStart( );		
		setApenasPaginas( );
	}
	
	@Override
	public void visit( Page page ) 
	{
		try 
		{
			if( page.getParseData( ) instanceof HtmlParseData )
			{
				String html = ((HtmlParseData)page.getParseData( )).getHtml( ).replaceAll( "\r", "" ).replaceAll( "\n", "" );
				
				String nome  = ER.buscaExprecao( html, "<div class=\"apphub_AppName\">(.*?)</div>" );
				String valor = ER.buscaExprecao( html, "<div class=\"game_purchase_price price\".*?itemprop=\"price\">(.*?)</div>" );
				valor = Web.filter( valor );
				
				String newPageBr  = Web.novaInstacia( ).get( page.getWebURL( ).getURL( ).concat( "?l=brazilian" ) );
				String lancamento = ER.buscaExprecao( newPageBr, "<b>Data de.*?</b>(.*?)<br>" );
				
				if( StringUtils.isNotEmpty( lancamento ) )
				{
					lancamento = lancamento.trim( );
				}
				
				Game game = new Game( );
				
				game.setDataVisita( Calendar.getInstance( )     );
				game.setNome      ( nome                        );
				game.setPrecoAtu  ( valor                       );
				game.setUrl       ( page.getWebURL( ).getURL( ) );
				game.setLancamento( lancamento                  );
				
				if( DAOFactory.infDao( ).save( game ) )
				{
					DAOFactory.infDao( ).remove( "SeedsToNavigate d where d.url = '" + page.getWebURL( ).getURL( ) + "'" );
				}
			}
		}
		catch( Exception e )
		{
			e.printStackTrace( );
		}
	}
}